// pages/index/vip.js
const auth = require('../../utils/auth.js')
const VipService = require('../../services/vip.js')
const CardService = require('../../services/card.js')

Page({
    /**
     * 页面的初始数据
     */
    data: {
        isLoggedIn: false,
        userInfo: null,
        loginReady: false,
        packages: [],
        selectedPackage: {},
        vipStatus: {
            isVip: false,
            expireDate: '',
            expire_time: 0
        },
        loading: false,
        currentMoney: 0,
        rights: [],

        indicatorDots:false,
        autoplay:false,
        interval:2000,
        duration:500,
        circular:true,

        topicList: [],
        recentOrders: [],
        currentOrderIndex: 0, // 当前显示的订单索引
        displayOrders: [], // 当前显示的订单组
        orderTimer: null, // 定时器

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.checkLoginStatus()
        this.loadVipData()
        this.loadTopicList()
        this.loadRecentOrders()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 页面显示时检查登录状态
        if (this.data.loginReady) {
            this.checkLoginStatus()
            this.loadVipData()
            this.loadRecentOrders()
        }
        this.loadTopicList()
    },

    async loadRecentOrders() {
        const recentOrdersResult = await VipService.recentOrders({ showLoading: false })
        if (recentOrdersResult.success) {
            this.setData({ recentOrders: recentOrdersResult.data })
            this.startOrderRotation()
        }
    },

    /**
     * 开始订单轮播
     */
    startOrderRotation() {
        // 清除之前的定时器
        if (this.data.orderTimer) {
            clearInterval(this.data.orderTimer)
        }

        const { recentOrders } = this.data
        if (!recentOrders || recentOrders.length === 0) {
            return
        }

        // 初始化显示第一组
        this.updateDisplayOrders()

        // 设置定时器，每2秒切换一组
        const timer = setInterval(() => {
            this.nextOrderGroup()
        }, 2000)

        this.setData({ orderTimer: timer })
    },

    /**
     * 更新显示的订单组
     */
    updateDisplayOrders() {
        const { recentOrders, currentOrderIndex } = this.data
        const groupSize = 1 // 每组显示1个订单
        const startIndex = currentOrderIndex * groupSize
        const endIndex = Math.min(startIndex + groupSize, recentOrders.length)
        
        const displayOrders = recentOrders.slice(startIndex, endIndex)
        this.setData({ displayOrders })
    },

    /**
     * 切换到下一组订单
     */
    nextOrderGroup() {
        const { recentOrders, currentOrderIndex } = this.data
        const groupSize = 1 // 每组显示1个订单
        const totalGroups = Math.ceil(recentOrders.length / groupSize)
        
        let nextIndex = currentOrderIndex + 1
        if (nextIndex >= totalGroups) {
            nextIndex = 0 // 循环到第一组
        }

        // 使用更平滑的切换方式
        this.setData({ 
            currentOrderIndex: nextIndex,
            displayOrders: [] // 先清空
        })

        // 短暂延迟后显示新内容，实现平滑切换
        setTimeout(() => {
            this.updateDisplayOrders()
        }, 100)
    },

    /**
   * 导航栏返回按钮事件
   */
  onNavbarBack() {
    wx.navigateBack({
      delta: 1
    });
  },

    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
        try {
            const loginStatus = await auth.checkLoginStatus()

            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                userInfo: loginStatus.userInfo,
                loginReady: true
            })
        } catch (error) {
            this.setData({
                isLoggedIn: false,
                userInfo: null,
                loginReady: true
            })
        }
    },

    /**
     * 加载VIP数据
     */
    async loadVipData() {
        try {
            // 加载VIP套餐
            const packagesResult = await VipService.getPackages({ showLoading: true })
            if (packagesResult.success) {
                this.setData({
                    packages: packagesResult.data.packages,
                    rights: packagesResult.data.rights
                })
                // 默认选择第一个套餐
                if (packagesResult.data.packages.length > 0) {
                    this.setData({
                        selectedPackage: packagesResult.data.packages[0]
                    })
                }
            }

            // 如果已登录，加载VIP状态
            if (this.data.isLoggedIn) {
                const statusResult = await VipService.getStatus({ showLoading: false })
                if (statusResult.success) {
                    const vipStatus = statusResult.data
                    let expireDate = ''
                    
                    if (vipStatus.is_vip && vipStatus.vip_expire_time) {
                        const date = new Date(vipStatus.vip_expire_time * 1000)
                        expireDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
                    }

                    this.setData({
                        vipStatus: {
                            isVip: vipStatus.is_vip,
                            expireDate: expireDate,
                            expire_time: vipStatus.expire_time
                        }
                    })
                }
            }
        } catch (error) {
            console.error('加载VIP数据失败:', error)
        }
    },

    /**
     * 自动登录完成回调
     * 由app.js调用
     */
    onAutoLoginComplete(isLoggedIn, userInfo) {
        console.log('VIP页面收到登录状态更新:', { isLoggedIn, userInfo });
        this.setData({
            isLoggedIn: isLoggedIn,
            userInfo: userInfo,
            loginReady: true
        });

        // 登录状态更新后重新加载数据
        this.loadVipData()
    },


    onPackageChange(e) {
        const index = e.detail.current
        this.setData({
            selectedPackage: this.data.packages[index]
        })
    },

    async loadTopicList() {
        const result = await CardService.getAllTopics({ showLoading: false })
        if (result.success) {
            this.setData({ topicList: result.data })
        }
    },

    /**
     * 购买VIP
     */
    async buyVip() {
        const { isLoggedIn, userInfo, selectedPackage } = this.data
        

        if (!isLoggedIn) {
            // 未登录，尝试自动登录
            this.autoLogin()
            return
        }

        if (!userInfo.phone || userInfo.phone.trim() === '') {
            // 已授权但手机号未绑定，跳转到登录页面
            wx.navigateTo({
                url: '/pages/index/login'
            })
            return
        }

        if (!selectedPackage.id) {
            wx.showToast({
                title: '请选择VIP套餐',
                icon: 'none'
            })
            return
        }

        // 如果已经是VIP，提示用户
        if (this.data.vipStatus.isVip) {
            wx.showModal({
                title: '提示',
                content: '您已经是VIP会员，是否要续费？',
                success: (res) => {
                    if (res.confirm) {
                        this.createVipOrder()
                    }
                }
            })
            return
        }

        this.createVipOrder()
    },

    /**
     * 创建VIP订单
     */
    async createVipOrder() {
        const { selectedPackage } = this.data

        try {
            this.setData({ loading: true })

            // 创建订单
            const orderResult = await VipService.createOrder({
                packageId: selectedPackage.id,
                showLoading: true
            })

            if (orderResult.success) {
                wx.requestPayment({
                    timeStamp: orderResult.data.config.timeStamp,
                    nonceStr: orderResult.data.config.nonceStr,
                    package: orderResult.data.config.package,
                    signType: orderResult.data.config.signType,
                    paySign: orderResult.data.config.paySign,
                    'success': (r) => {
                        if (r.errMsg == 'requestPayment:ok') {
                            wx.showToast({
                                title: '购买成功',
                                icon: 'success'
                            })
        
                            // 重新加载VIP状态
                            setTimeout(() => {
                                this.loadVipData()
                            }, 1000)
                        }
                    },
                    'fail': (r) => {
                        wx.showToast({ title: '支付失败', icon: 'none' });
                    }
                })
            } else {
                wx.showModal({
                    title: '创建订单失败',
                    content: orderResult.message,
                    showCancel: false
                })
            }
        } catch (error) {
            console.error('购买VIP失败:', error)
            wx.showModal({
                title: '购买失败',
                content: '网络错误，请重试',
                showCancel: false
            })
        } finally {
            this.setData({ loading: false })
        }
    },

    /**
     * 自动登录
     */
    async autoLogin() {
        try {
            wx.showLoading({ title: '登录中...', mask: true })

            const loginResult = await auth.login()

            if (loginResult.success) {
                // 登录成功
                this.setData({
                    isLoggedIn: true,
                    userInfo: loginResult.userInfo
                })

                wx.showToast({
                    title: '登录成功',
                    icon: 'success'
                })

                // 重新加载数据
                this.loadVipData()
            } else {
                // 登录失败
                wx.showModal({
                    title: '登录失败',
                    content: loginResult.message || '请重试',
                    showCancel: false
                })
            }
        } catch (error) {
            console.error('自动登录失败:', error)
            wx.showModal({
                title: '登录失败',
                content: '网络错误，请重试',
                showCancel: false
            })
        } finally {
            wx.hideLoading()
        }
    },

    /**
     * 跳转到登录页面
     */
    goToLogin() {
        wx.navigateTo({
            url: '/pages/index/login'
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        // 页面隐藏时清除定时器
        if (this.data.orderTimer) {
            clearInterval(this.data.orderTimer)
            this.setData({ orderTimer: null })
        }
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        // 页面卸载时清除定时器
        if (this.data.orderTimer) {
            clearInterval(this.data.orderTimer)
            this.setData({ orderTimer: null })
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})